package com.project.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@RestController
@RequestMapping("cookie")
public class CookieController {

    @RequestMapping("add")
    public String addCookie(HttpServletResponse resp){
        //创建Cookie对象，并封装发送给客户端的信息
        Cookie c = new Cookie("name","tiger");
        //在响应信息中，添加cookie信息,放在客户端浏览器缓存中
        resp.addCookie(c);

        Cookie c1 = new Cookie("age","20");
        //设置过期时间，cookie会以文件方式发送给服务器
        c1.setMaxAge(120);
        resp.addCookie(c1);

        return "添加成功";
    }

    @RequestMapping("get")
    public String getCookie(HttpServletRequest req){
        //得到客户端请求的cookie信息
        Cookie[] cookieArray = req.getCookies();
        String str = "";
        for(Cookie c : cookieArray){
            str += "键："+c.getName()+"   值："+c.getValue()+"<br>";
        }
        return str;
    }
}
